package com.aaron.android.battery;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public final class BatteryInfoWidgetProvider extends AppWidgetProvider {

	private Intent _intent = null;
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);

		initializeIntent(context);
		context.stopService(_intent);
	}

	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);
		initializeIntent(context);
		context.stopService(_intent);
	}

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		initializeIntent(context);
		startBatteryInfoWidgetService(context);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		initializeIntent(context);

		startBatteryInfoWidgetService(context);
	}

	private void startBatteryInfoWidgetService(Context context) {
		try {
			context.startService(_intent);
		} catch (Exception e) {
			Log.d("BatteryInfoProvider", "Start battery widget service failed.", e);
			Toast.makeText(context,
					context.getResources().getText(R.string.error_show), 1000)
					.show();
		}
	}

	private void initializeIntent(Context context) {
		if (_intent == null) {
			_intent = new Intent(context, BatteryInfoWidgetService.class);
		}
	}
}
